package com.example.qxfw.dysjrh.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import com.example.qxfw.common.service.FileRequestService;
import com.example.qxfw.common.util.GetPath;
import com.example.qxfw.dysjrh.config.DmgisConfig;
import com.example.qxfw.dysjrh.entity.LdPngFile;
import com.example.qxfw.dysjrh.entity.SatelliteData;
import com.example.qxfw.dysjrh.entity.YtPngFile;
import com.example.qxfw.dysjrh.entity.vo.SatelliteNephoramVO;
import com.example.qxfw.dysjrh.mapper.SatelliteMapper;
import com.example.qxfw.dysjrh.service.SatelliteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import org.springframework.data.mongodb.core.query.Query;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wzt
 * @date 2024/12/13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SatelliteServiceImpl implements SatelliteService {

    @Autowired
    @Mapper
    private SatelliteMapper satelliteMapper;

    private final DmgisConfig dmgisConfig;

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;


    private String GettqFilepath() {
        String tqFilepath = "";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            tqFilepath = dmgisConfig.getWinpath();
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            tqFilepath = dmgisConfig.getLinuxpath();
        }
        return tqFilepath;
    }

    @Override
    public List<SatelliteNephoramVO> getSatelliteData(SatelliteData satelliteData) {
        LocalDateTime startTime = satelliteData.getStartTime();

        LocalDateTime endTime = satelliteData.getEndTime();

        String satelliteType = satelliteData.getYtType();
        String ytType = "";

        switch(satelliteType){
            case "0":
                ytType = "FY2G可见光图像";
                break;
            case "1":
                ytType = "FY2G红外图像";
                break;
            case "2":
                ytType = "FY2G分裂窗图像";
                break;
            case "3":
                ytType = "FY2G水汽图像";
                break;
            case "4":
                ytType = "FY2G中红外图像";
                break;
            case "5":
                ytType = "FY4B真彩色";
                break;
        }
        try {
            List<SatelliteNephoramVO> satelliteDataList = satelliteMapper.getSatelliteData_FY2G(startTime, endTime, ytType);
            if (satelliteDataList == null){
                log.info("pg数据库查询失败");
            }
            for (SatelliteNephoramVO satelliteVo : satelliteDataList) {
                String datacharTime = satelliteVo.getDateChar().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                //查询mongo中的图片地址
                Query query = new Query();
                //添加条件：

//                query.addCriteria(Criteria.where("dateyear").is("2025"));
//                query.addCriteria(Criteria.where("datechar").is("2025-01-13"));
//                query.addCriteria(Criteria.where("timechar").is("0018"));
//                query.addCriteria(Criteria.where("yttype").is("FY2G分裂窗图像"));

//                query.addCriteria(Criteria.where("dateyear").is(satelliteVo.getDataYear().toString()));
//                query.addCriteria(Criteria.where("datechar").is(datacharTime));
//                query.addCriteria(Criteria.where("timechar").is(satelliteVo.getTimeChar()));
//                query.addCriteria(Criteria.where("yttype").is(satelliteVo.getYtType()));
//
//                YtPngFile ytPngFile = mongoTemplate.findOne(query, YtPngFile.class);
////                System.out.println(ytPngFile);
////                System.out.println("-----------");
//
//
//                if (ytPngFile == null) continue;
//                String imageName = ytPngFile.get_id();
//                String fileName = dmgisConfig.getTxtFilePath() + imageName + ".png";
//                satelliteVo.setImagePath(dmgisConfig.getNgfileUrl() + imageName + ".png");
//                // 删除文件
//                FileUtil.del(fileName);
//                //创建文件
//                FileUtil.touch(fileName);
//                FileUtil.writeBytes(ytPngFile.getData(), new File(fileName));

                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("collectionName", "yt_png_file");
                queryMap.put("datechar", datacharTime);
                queryMap.put("timechar", satelliteVo.getTimeChar());
                queryMap.put("yttype", satelliteVo.getYtType());
                queryMap.put("advCode", "");

//                Map<String, Object> queryMap = new HashMap<>();
//                queryMap.put("collectionName", "yt_png_file");
//                queryMap.put("datechar", "2025-01-14");
//                queryMap.put("timechar", "1718");
//                queryMap.put("yttype", "FY2G红外图像");
//                queryMap.put("advCode", "");


//                String path = selectPath(queryMap);

                byte[] bytes = selectData(queryMap);

                String path2 = "DmgisPubData/dmgis_xjservice_file/yt_png_file" + "/" + datacharTime + "/" + satelliteVo.getTimeChar() + "/" + satelliteVo.getYtType() + ".png";
//                String path2 = "DmgisPubData/dmgis_xjservice_file/yt_png_file" + "/" + "2025-01-14" + "/" + "1718" + "/" + "FY2G红外图像" + ".png";

                String fileName = dmgisConfig.getTxtFilePath() + path2 ;
                 //删除文件
                FileUtil.del(fileName);
                //创建文件
                FileUtil.touch(fileName);
                FileUtil.writeBytes(bytes, new File(fileName));


                String imagePath = dmgisConfig.getNgfileUrl() + path2;

                satelliteVo.setImagePath(imagePath);
            }
            return satelliteDataList;
        } catch (IORuntimeException e) {
            throw new RuntimeException("Failed to fetch radar data", e);
        }
    }


    public String selectPath(Map<String, Object> queryMap) {
//        String dbName = DbConfig.dbname;
        String dbName = dmgisConfig.getDbname();
        String collectionName = (String)queryMap.get("collectionName");
        queryMap.remove("collectionName");
//        if (!StringUtil.IsNullOrEmpty((String)queryMap.get("advCode"))) {
        String advCode = (String)queryMap.get("advCode");
        if (Objects.nonNull(advCode) && !advCode.isEmpty()) {
            dbName = dbName + "_" + queryMap.get("advCode");
            queryMap.remove("advCode");
        }

//        String basePath = GettqFilepath();
        String basePath = dmgisConfig.getWinpath();
        String filePath = basePath  +  "DmgisPubData" + File.separator + dbName + File.separator + collectionName + File.separator;
        filePath = GetPath.action(queryMap, filePath, collectionName);
        return filePath;
    }


    public byte[] selectData(Map<String, Object> queryMap) {
        String dbName = dmgisConfig.getDbname();
        String collectionName = (String)queryMap.get("collectionName");
        queryMap.remove("collectionName");
//        if (!StringUtil.IsNullOrEmpty((String)queryMap.get("advCode"))) {
        String advCode = (String)queryMap.get("advCode");
        if (Objects.nonNull(advCode) && !advCode.isEmpty()) {
            dbName = dbName + "_" + queryMap.get("advCode");
            queryMap.remove("advCode");
        }

        byte[] result = null;
        String basePath = GettqFilepath();
        String filePath = basePath + File.separator +  "DmgisPubData" + File.separator + dbName + File.separator + collectionName + File.separator;
        filePath = GetPath.action(queryMap, filePath, collectionName);
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            try {
                InputStream in = new FileInputStream(filePath);
                byte[] filebyte = IOUtils.toByteArray(in);
                in.close();
                result = filebyte;
            } catch (IOException var10) {
                var10.printStackTrace();
            }
        } else {
            System.out.println("文件不存在");
        }

        return result;
    }



}
